import { useContext, useEffect, useState } from 'react';
import type { IPost, IQueryParams, IUserClientDetails } from '@/interfaces';
import { toRelativeTime } from '@/lib/tool';
import { useInfiniteQuery } from '@tanstack/react-query';
import { clientQueryUserDetails } from '@/services/api';
import { UserIdH5PageContext } from '@/contexts/mobile/userId';
import Link from 'next/link';
import classNames from 'classnames';
import useUser from '@/hooks/useUser';
import useToast from 'hooks/useToast';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import { useSearchParams } from 'next/navigation';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import PostName from '@/app/[locale]/common/post/name';
import PostOverview from '@/app/[locale]/common/post/overview';
import PostReadMoreBtn from '@/app/[locale]/common/post/readMore';
import PostTime from '@/app/[locale]/common/post/time';

export default function PostUserIdH5Page(
  this: any,
  {
    id,
    type = 'post',
  }: {
    id: number;
    type?: 'post' | 'section' | 'tag';
  },
) {
  const context = useContext(UserIdH5PageContext);
  const metadata = context.metadata!;
  const [pages, setPages] = useState<IPost[]>(
    (metadata.all['userId'].v as IUserClientDetails).data.content,
  );
  const { show } = useToast();
  const urlSearchParams = useSearchParams();
  const sectionIdParam =
    urlSearchParams.get('sectionId') ?? urlSearchParams.get('sid');
  const tagIdParam = urlSearchParams.get('tagId') ?? urlSearchParams.get('tid');
  const userQuery = useUser(metadata);

  const clientQueryUserDetailsQuery = useInfiniteQuery(
    metadata.all['userId'].k,
    async (context) => {
      return (await clientQueryUserDetails({
        id: context.queryKey[2] + '',
        query: {
          ...(context.queryKey[4] as IQueryParams),
          ...context.pageParam,
        },
      })) as IUserClientDetails;
    },
    {
      enabled: !!(
        id &&
        metadata.all['userId'] &&
        id === metadata.all['userId'].k[2]
      ),
      keepPreviousData: true,
      getPreviousPageParam: (firstPage) => {
        if (firstPage.data && firstPage.data.pageable.previous) {
          return {
            page: Math.max(firstPage.data.pageable.page - 1, 0),
          };
        }
      },
      getNextPageParam: (lastPage) => {
        if (lastPage.data && lastPage.data.pageable.next) {
          return {
            page: Math.min(
              lastPage.data.pageable.page + 1,
              lastPage.data.pageable.pages,
            ),
          };
        }
      },
      initialData: () => {
        if (metadata.all['userId']) {
          return {
            pages: [metadata.all['userId'].v as IUserClientDetails],
            pageParams: [
              {
                page: Math.max(
                  ((metadata.all['userId'].k[4] as IQueryParams).page ?? 1) - 1,
                  0,
                ),
              },
            ],
          };
        }
      },
    },
  );

  useEffect(() => {
    if (clientQueryUserDetailsQuery.data) {
      setPages(
        clientQueryUserDetailsQuery.data.pages
          .flatMap((item) => item.data?.content ?? [])
          .map((item) => {
            item._contentUpdatedOnText = toRelativeTime(item.contentUpdatedOn);
            return item;
          }),
      );
    }
  }, [clientQueryUserDetailsQuery.data]);

  async function onClickLoadMore() {
    try {
      await clientQueryUserDetailsQuery.fetchNextPage();
    } catch (e) {
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  if (clientQueryUserDetailsQuery.data) {
    const sections = clientQueryUserDetailsQuery.data.pages[0].sections;
    const tags = clientQueryUserDetailsQuery.data.pages[0].tags;

    return (
      <div className="vstack gap-4">
        {type === 'section' && (
          <div className="my-4 d-flex gap-4 flex-nowrap text-nowrap overflow-x-auto pb-3">
            {sections.map((item) => {
              return (
                <div key={item.id} className="card flex-shrink-0">
                  <div className="list-group list-group-flush text-center">
                    <Link
                      href={`/users/home?sectionId=${item.id}`}
                      className={classNames(
                        'list-group-item list-group-item-action py-3',
                        {
                          active: sectionIdParam === item.id + '',
                        },
                      )}
                    >
                      {item.name}
                    </Link>
                  </div>
                </div>
              );
            })}

            <div className="card flex-shrink-0">
              <div className="list-group list-group-flush text-center">
                <Link
                  href="/users/home"
                  className={classNames(
                    'list-group-item list-group-item-action py-3',
                    {
                      disabled: sections.length === 0,
                    },
                  )}
                >
                  全部
                </Link>
              </div>
            </div>
          </div>
        )}

        {type === 'tag' && (
          <div className="my-4 hstack gap-4 flex-nowrap overflow-x-auto text-nowrap pb-3">
            {tags.map((item) => {
              return (
                <div key={item.id} className="card flex-shrink-0">
                  <div className="list-group list-group-flush text-center">
                    <Link
                      href={`/users/home?tagId=${item.id}`}
                      className={classNames(
                        'list-group-item list-group-item-action',
                        {
                          active: tagIdParam === item.id + '',
                        },
                      )}
                    >
                      {item.name}
                    </Link>
                  </div>
                </div>
              );
            })}

            <div className="card flex-shrink-0">
              <div className="list-group list-group-flush text-center">
                <Link
                  href="/users/home"
                  className={classNames(
                    'list-group-item list-group-item-action',
                    {
                      disabled: tags.length === 0,
                    },
                  )}
                >
                  全部
                </Link>
              </div>
            </div>
          </div>
        )}

        {pages.map((item) => {
          const style = (item.styles || []).find(
            (value) => value.type === 'NAME',
          );

          return (
            <div className="row" key={item.id}>
              <div className="col-12">
                <div className="yw-bg" style={{ height: '0.35rem' }}></div>
              </div>
              <div className="col-12 bg-white rounded-3 py-4">
                <div className="vstack gap-4 align-items-center">
                  <PostName
                    item={item}
                    isFwSemibold={false}
                    isJustifyContentCenter
                  />

                  <PostOverview item={item} bodClassName="my-4" />

                  <PostReadMoreBtn
                    item={item}
                    isEdit={
                      userQuery.data &&
                      userQuery.data.user &&
                      userQuery.data.user.id === item.createdBy
                    }
                  />

                  <PostTime item={item} />
                </div>
              </div>
            </div>
          );
        })}

        {pages.length === 0 ? (
          <Nodata />
        ) : (
          <LoadMoreBtn
            onClickLoadMore={onClickLoadMore}
            isDisabled={
              !clientQueryUserDetailsQuery.hasNextPage ||
              clientQueryUserDetailsQuery.isFetchingNextPage
            }
            isFetchingNextPage={clientQueryUserDetailsQuery.isFetchingNextPage}
          />
        )}
      </div>
    );
  }

  if (clientQueryUserDetailsQuery.error) {
    return <Alert message={clientQueryUserDetailsQuery.error} type="error" />;
  }

  return <AlertLoad />;
}

const ReadMoreBtn = ({
  id,
  createdBy,
}: {
  id: number;
  createdBy: number | undefined;
}) => {
  const context = useContext(UserIdH5PageContext);
  const metadata = context.metadata!;
  const userQuery = useUser(metadata);

  return (
    <>
      {userQuery.data &&
      userQuery.data.user &&
      userQuery.data.user.id === createdBy ? (
        <Link className="btn btn-primary" href={`/posts/${id}/edit`}>
          <i className="bi bi-pencil-square me-2"></i>
          编辑帖子
        </Link>
      ) : (
        <Link className="btn btn-primary" href={`/posts/${id}`}>
          阅读更多
        </Link>
      )}
    </>
  );
};

const LoadMoreBtn = ({
  onClickLoadMore,
  isDisabled,
  isFetchingNextPage,
}: {
  onClickLoadMore: () => void;
  isDisabled: boolean;
  isFetchingNextPage: boolean;
}) => {
  return (
    <div className="row mt-4 mb-3">
      <div className="col">
        <button
          onClick={onClickLoadMore}
          disabled={isDisabled}
          type="button"
          className="btn rounded-pill btn-light w-100 text-secondary"
        >
          {isFetchingNextPage ? (
            <>
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
              Loading...
            </>
          ) : (
            <i className="bi bi-three-dots me-2"></i>
          )}
        </button>
      </div>
    </div>
  );
};
